#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: data_destory_base.py 
@version:
@time: 2022/03/16 
"""
from TapClientCaseData.TableGenerateData.generate_data.data_generate_base import *


class DataDestroyBase:

    async def drop_template(self, data):
        test_table_type = data.get('test_table_type')
        filter = {
            'name': test_table_type,
            'db_name': data.get('db_info').get('name')
        }
        query_result = MFA.query(parallel_record_collection, filter)
        for i in query_result:
            await self._drop_table(
                data,
                i.get('table')
            )
            MFA.delete_one(parallel_record_collection, filter)

    async def drop_more_table_template(self, data):
        test_table_type = data.get('test_table_type')
        filter = {
            'name': test_table_type,
            'db_name': data.get('db_info').get('name')
        }
        query_result = MFA.query(parallel_record_collection, filter)
        if query_result:
            for i in query_result[0].get('table'):
                await self._drop_table(
                    data,
                    i
                )
        MFA.delete_one(parallel_record_collection, filter)

    @staticmethod
    async def _drop_table(data, table):
        db_info = data.get('db_info')
        source = TapClientConnector(db_info)
        _drop_ = source.tapclient_connector.generate_drop(table)
        try:
            source.tapclient_connector.exec(_drop_)
        except:
            pass

    def target_drop_table(self, db_info, source_type, name):
        import inspect

        def get_classes(arg):
            classes = {}
            cls_members = inspect.getmembers(arg, inspect.isclass)
            for name, _ in cls_members:
                classes.update({name: _})
            return classes

        db_info = getattr(get_classes(db_info).get(source_type), name)
        connector = TapClientConnector(db_info)
        table_list = connector.tapclient_connector.show_tables()
        import asyncio
        async_run = asyncio.get_event_loop().run_until_complete
        async_run(self._drop_all_table_(connector, table_list))

    @staticmethod
    async def _drop_all_table_(connector, table_list):
        for table in table_list:
            if connector.database_type in ['elasticsearch']:
                table = table.lower()
            for raw_table in connector.tapclient_connector.show_tables():
                if table == raw_table:
                    drop_operate = connector.tapclient_connector.generate_drop(table)
                    connector.tapclient_connector.exec(drop_operate)
                    break
